import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface CartItem {
  id: number | string
  name: string
  price: number
  quantity: number
  image: string
  checked: boolean
  specs?: string
  skuId?: string
  skuData?: {
    Id: string
    title: string
    price: number
    stock: number
    status: number
  }
}

export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])

  // 计算属性
  const totalItems = computed(() =>
    items.value.reduce((total, item) => total + item.quantity, 0)
  )

  const totalPrice = computed(() =>
    items.value
      .filter(item => item.checked)
      .reduce((total, item) => total + item.price * item.quantity, 0)
  )

  const checkedItems = computed(() =>
    items.value.filter(item => item.checked)
  )

  const checkedItemsCount = computed(() =>
    checkedItems.value.reduce((total, item) => total + item.quantity, 0)
  )

  // 添加產品到购物车
  const addToCart = (product: Omit<CartItem, 'quantity' | 'checked'>) => {
    const existingItem = items.value.find(item =>
      item.id === product.id &&
      item.specs === product.specs &&
      item.skuId === product.skuId
    )

    if (existingItem) {
      existingItem.quantity += 1
      // 更新SKU数据（如果有的话）
      if (product.skuData) {
        existingItem.skuData = product.skuData
      }
    } else {
      items.value.push({
        ...product,
        quantity: 1,
        checked: true
      })
    }

    // 保存到本地存储
    saveToLocalStorage()
  }

  // 移除產品
  const removeFromCart = (id: number | string, specs?: string) => {
    const index = items.value.findIndex(item =>
      item.id === id && item.specs === specs
    )

    if (index > -1) {
      items.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 更新產品数量
  const updateQuantity = (id: number | string, quantity: number, specs?: string) => {
    const item = items.value.find(item =>
      item.id === id && item.specs === specs
    )

    if (item) {
      if (quantity <= 0) {
        removeFromCart(id, specs)
      } else {
        item.quantity = quantity
        saveToLocalStorage()
      }
    }
  }

  // 切换產品选中状态
  const toggleItemCheck = (id: number | string, specs?: string) => {
    const item = items.value.find(item =>
      item.id === id && item.specs === specs
    )

    if (item) {
      item.checked = !item.checked
      saveToLocalStorage()
    }
  }

  // 全选/取消全选
  const toggleAllCheck = (checked: boolean) => {
    items.value.forEach(item => {
      item.checked = checked
    })
    saveToLocalStorage()
  }

  // 清空购物车
  const clearCart = () => {
    items.value = []
    saveToLocalStorage()
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('cart', JSON.stringify(items.value))
  }

  // 从本地存储恢复
  const loadFromLocalStorage = () => {
    const savedCart = localStorage.getItem('cart')
    if (savedCart) {
      items.value = JSON.parse(savedCart)
    }
  }

  // 结算选中產品
  const checkout = () => {
    const selectedItems = checkedItems.value
    if (selectedItems.length === 0) {
      return { success: false, message: '請選擇要結算的產品' }
    }

    // 模拟结算过程
    // 实际项目中这里应该调用结算API
    return {
      success: true,
      message: '訂單提交成功',
      items: selectedItems,
      total: totalPrice.value
    }
  }

  return {
    items,
    totalItems,
    totalPrice,
    checkedItems,
    checkedItemsCount,
    addToCart,
    removeFromCart,
    updateQuantity,
    toggleItemCheck,
    toggleAllCheck,
    clearCart,
    loadFromLocalStorage,
    checkout
  }
})
